<template>
    <div>
         <el-card class="box-card">
            <div slot="header" class="clearfix">
                <el-tag type="primary" v-if="form.gatewayGroup">网关分组[{{form.gatewayGroup}}]</el-tag>
                <span class="title">{{formTitle}}</span>
            </div>
        <div style="margin: 15px">
            <h3>
                <i class="el-icon-edit-outline"></i>
                基础信息
            </h3>
        </div>
            <el-form :model="form" label-width="130px" :rules="rules" ref="form" :disabled="mode==='view'">
            <el-form-item label="网关分组" required prop="gatewayGroup">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-select v-model="form.gatewayGroup" placeholder="请选择" size="small">
                            <el-option
                                v-for="item in groupList"
                                :key="item.groupId"
                                :label="`${item.groupName}(${item.groupId})`"
                                :value="item.groupId">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item label="回调方式" required prop="callbackType">
                <el-radio-group v-model="form.callbackType">
                    <el-radio label="s">同步</el-radio>
                    <el-radio label="a">异步</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="访问" required prop="access">
                <el-radio-group v-model="form.access">
                    <el-radio label="a">允许</el-radio>
                    <el-radio label="f">禁止</el-radio>
                </el-radio-group>
            </el-form-item>
            <template v-if="form.callbackType==='a'">
                <el-row :gutter="20" v-for="(item,index) in form.callbackRespHeaders" :key="item.valule" required>
                  <el-col :span="5">
                     <el-form-item :label="`响应头${index+1}`" required prop="key" :rules="{required: true, message: '字段名不能为空', trigger: 'blur'}">
                        <el-input v-model="item.key" placeholder="字段名(例:content-type)" size="small"></el-input>
                     </el-form-item>
                  </el-col>
                  <el-col :span="5">
                     <el-form-item label-width="0" required prop="value" :rules="{required: true, message: '字段值不能为空', trigger: 'blur'}">
                        <el-input v-model="item.value" placeholder="字段值(例:application/js)" size="small"></el-input>
                     </el-form-item>
                  </el-col>
                  <el-col :span="2">
                       <el-form-item label-width="0">
                           <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddRes" v-if="index===0"></el-button>
                           <el-button type="danger" icon="el-icon-delete" circle size="mini" v-else @click="removeRes(item)"></el-button>
                       </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="响应体" required>
                    <el-row>
                    <el-col :span="20">   
                        <el-input v-model="form.callbackRespBody" placeholder="例：{'name':'wei'}" type="textarea" :rows="3" :rules="{
                            required: true, message: '必填', trigger: 'blur'}"></el-input>
                    </el-col>
                    </el-row>
                </el-form-item>
            </template>
            <el-form-item label="请求方法">
               <el-select v-model="form.method" placeholder="请选择" size="small">
                    <el-option v-for="item in methods" :key="item" :label="item" :value="item"></el-option>
               </el-select>
            </el-form-item>
            <el-form-item label="前端服务名" required prop="service">
                <el-input v-model="form.service" placeholder="请输入服务名" size="small"></el-input>
            </el-form-item>
            <el-form-item label="前端路径" required prop="path">
                <el-row :gutter="10">
                    <el-col :span="18">
                        <el-input v-model="form.path" placeholder="请输入后端API路径" size="small" clearable></el-input>
                        <div style="font-size: 10px;opacity: .7;">
                            调用方访问路径，不支持模糊匹配，如：/member/getMebInfo
                        </div>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                  <el-button type="primary" icon="el-icon-plus" size="small" @click="addSubscribe">新增后端订阅者</el-button>
              </el-col>
            </el-row>
              <el-row :gutter="20" v-for="(item,index) in form.callbackReceivers" :key="index">
                  <el-col :span="5">
                       <el-form-item :label="`【后端订阅者${index+1}】类型：`" label-width="200px" required>
                            <el-radio-group v-model="item.type">
                                <el-radio :label="1">服务编排</el-radio>
                                <el-radio :label="0">服务发现</el-radio>
                           </el-radio-group>
                       </el-form-item>
                  </el-col>
                      <el-col :span="5">
                        <el-form-item label="服务名" label-width="80px" required prop="service" :rules="[
                                { required: true, message: '服务名不能为空', trigger: 'blur' }
                        ]">
                            <el-select v-model="item.service" placeholder="请选择" size="small">
                                <el-option v-for="item2 in serviceList" :key="item2.id" :label="item2.name" :value="item2.name"></el-option>
                            </el-select>
                        </el-form-item>
                      </el-col>
                    <el-col :span="5">
                        <el-form-item label="路径" label-width="60px" required prop="path" :rules="[
                                { required: true, message: '路径不能为空', trigger: 'blur' }
                            ]">
                            <el-input autocomplete="off" size="small" placeholder="发现目标路径,不支持模糊匹配" v-model="item.path"></el-input>
                        </el-form-item>
                    </el-col>
                  <el-col :span="2">
                      <el-form-item label-width="0">
                          <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="handleDetele(item)"></el-button>
                      </el-form-item>
                  </el-col>
               </el-row>
               <el-row>
                 <el-col :span="24">
                     <el-form-item label="调用方(appID):" prop="appEnabled">
                         <el-checkbox v-model="form.appEnabled">启用</el-checkbox>
                         <div style="font-size: 10px;opacity: .7;">限制调用方访问，请求URL需在请求头中加应用授权 (示例)，不启用不限制</div>
                         <div v-if="form.appEnabled">
                            <el-button type="primary" plain size="mini" @click="handleAddApp">添加</el-button>
                            <el-table :data="form.apps" size="mini" border style="width: 100%">
                                <el-table-column type="selection" width="55" prop="enabled"></el-table-column>
                                <el-table-column prop="app" label="appID"></el-table-column>
                                <el-table-column prop="appName" label="appName" v-if="false"></el-table-column>
                                <el-table-column label="操作"  width="100"> 
                                    <template slot-scope="scope">
                                        <el-button type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                         </div>
                     </el-form-item>
                 </el-col>
               </el-row>
            </el-form>
            <div style="margin: 15px">
                <h3>
                    <i class="el-icon-edit-outline"></i>
                    插件配置
                </h3>
                  <div style="margin: 10px 0">
                  <span style="font-size: 10px">网关分组级别的插件对分组下所有路由都生效</span>
                  <div style="margin-top: 20px">
                       <el-button type="primary" plain size="small" @click="addPlugin" :disabled="mode==='view'">添加插件</el-button>
                  </div>
                   <el-collapse style="padding: 20px">
                    <el-collapse-item :name="item.id" v-for="(item,index) in form.apiPlugins" :key="index" :disabled="!item.instruction || mode==='view'">      
                         <template slot="title">
                            {{index+1}} #【路由级别】{{item.chnName}}
                            <el-tag style="margin: 0 10px" type="success" size="small">执行顺序</el-tag>
                             <el-input-number v-model="item.order" size="mini" controls-position="right" :disabled="mode==='view'"></el-input-number>
                             <template v-if="item.instion">
                                 <el-tag style="margin: 0 10px" type="success" size="small">配置</el-tag>
                                 <el-tooltip class="item" effect="dark" :content="item.instruction" placement="top">
                                    <div>
                                        <i class="header-icon el-icon-info"></i>
                                        <el-button type="text">使用说明</el-button>
                                    </div>
                                 </el-tooltip>
                             </template>

                             <div class="detele-wrap"> 
                                <el-button type="danger" icon="el-icon-delete" circle size="mini" :disabled="mode==='view'"></el-button>
                              </div>
                        </template>
                         <template v-if="item.config">
                            <el-form :model="pluginForm">
                              <el-form-item v-for="item2 in JSON.parse(item.config)" :key="item2.field" :label="item2.label" :rules="item2.rules" :prop="item2['field']">
                                 <div v-if="item2.component==='textarea'">
                                    <el-input :rows="2" size="small" v-model="item2['field']" type="textarea"></el-input>
                                    <span style="font-size: 10px;opacity: .7">{{item2.desc}}</span>
                                </div>
                                 <div v-if="item2.component==='select'">
                                   <el-select size="small" v-model="item2['field']">
                                     <el-option v-for="(item3,index3) in item2.options" :key="index3" :label="item3.label" :value="item3.value"></el-option>
                                   </el-select>
                                </div>
                                 <div v-if="item2.component==='checkbox'">
                                    <div v-for="item3 in item2.options" :key="item3.label">
                                          <el-checkbox v-model="item2['field']">{{item3.label}}</el-checkbox>
                                    </div>
                                    <span style="font-size: 10px;opacity: .7">{{item2.desc}}</span>
                                </div>
                                <div v-if="item2.component==='input'">
                                    <el-input size="small" v-model="item2['field']"></el-input>
                                    <span style="font-size: 10px;opacity: .7">{{item2.desc}}</span>
                                </div>
                              </el-form-item>
                            </el-form>
                        </template>
                    </el-collapse-item>
               </el-collapse>
              </div>
        </div>
        <div style="margin-top: 20px;text-align: right" v-if="mode !== 'view'">
            <el-button type="primary" @click="handleSubmit('form')" size="small" icon="el-icon-search">保存</el-button>
            <el-button @click="clear()" icon="el-icon-delete" size="small">取消</el-button>
        </div>
        </el-card>
        <el-drawer
            title="添加调用方(appID)"
            :visible.sync="appDrawer"
            size="50%"
            direction="rtl"
            :before-close="handleClose">
            <el-form label-width="100px" :model="queryParams" ref="queryParams">
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="appID：" prop="app">
                        <el-input size="small" placeholder="appID" v-model="queryParams.app"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="应用名：" prop="appName">
                        <el-input size="small" placeholder="应用名" v-model="queryParams.appName"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="标签：" prop="tagCondition">
                        <el-input size="small" placeholder="标签" v-model="queryParams.tagCondition"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item >
                        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-delete" size="small" @click="resetQuery('queryParams')">清空</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="appData" ref="appRef" border size="small">
            <el-table-column type="selection" prop="enabled"></el-table-column>
            <el-table-column label="appID" prop="app"></el-table-column>
            <el-table-column label="应用名" prop="appName"></el-table-column>
            <el-table-column label="标签" prop="tags"></el-table-column>
        </el-table>
        <el-pagination
            v-show="appTotal>0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            :current-page="1"
            :page-sizes="[10, 20, 30, 40,50,100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            class="pagination-container"
            :total="appTotal">
        </el-pagination>
        <el-divider></el-divider>
        <div style="margin: 20px;text-align: right">
            <el-button type="primary" @click="addAppClick()" size="small" icon="el-icon-search">确定</el-button>
            <el-button icon="el-icon-delete" size="small" @click="appDrawer=false">取消</el-button>
        </div>
        </el-drawer>
        <el-drawer title="添加插件" :visible.sync="drawer" size="50%" direction="rtl">
            <div>
                <div style="padding: 10px">
                    <el-checkbox v-model="checkedList" @change="handleCheckAllChange">全选</el-checkbox>
                </div>                                           
               <el-collapse style="padding: 20px">
                    <el-collapse-item :name="item.id" v-for="item in pluginList" :key="item.id" :disabled="!item.instruction">                     
                        <template slot="title">
                            <el-checkbox v-model="item.check">{{item.chnName}}</el-checkbox>
                             <template v-if="item.instruction">
                                 <el-tag style="margin: 0 10px" type="success" size="small">配置</el-tag>
                                 <el-tooltip class="item" effect="dark" :content="item.instruction" placement="top">
                                    <div>
                                        <i class="header-icon el-icon-info"></i>
                                        <el-button type="text">使用说明</el-button>
                                    </div>
                                 </el-tooltip>
                             </template>
                        </template>
                        <template v-if="item.config">
                            <el-form disabled>
                              <el-form-item v-for="item2 in JSON.parse(item.config)" :key="item2.field" :label="item2.label" :rules="item2.rules">
                                 <div v-if="item2.component==='textarea'">
                                    <el-input :rows="2" type="textarea"></el-input>
                                    <span>{{item2.desc}}</span>
                                </div>
                                 <div v-if="item2.component==='select'">
                                   <el-select size="small" v-model="addForm.statusCode">
                                     <el-option v-for="(item3,index3) in item2.options" :key="index3" :label="item3.label" :value="item3.value"></el-option>
                                   </el-select>
                                </div>
                                 <div v-if="item2.component==='checkbox'">
                                    <div v-for="item3 in item2.options" :key="item3.label">
                                          <el-checkbox :label="item3.label"></el-checkbox>
                                    </div>
                                    <span>{{item2.desc}}</span>
                                </div>
                                <div v-if="item2.component==='input'">
                                    <el-input></el-input>
                                    <span>{{item2.desc}}</span>
                                </div>
                              </el-form-item>
                            </el-form>
                        </template>
                    </el-collapse-item>
                     <div style="text-align: right;margin-top: 10px;">
                        <el-button type="primary" @click="handleAddPlugin" size="small">添加</el-button>
                        <el-button @click="drawer = false" size="small">取消</el-button>
                    </div>
               </el-collapse>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import { getGroupList,getAppIdList,getServiceList,save,getDetail } from '@/api/callback/config.api.js';
import { getPluginListAll } from '@/api/getway/group.api.js'
    export default {
        name: 'CallBackDetail',
        data() {
            return {
                form: {
                    callbackType: 's',
                    access: 'a',
                    appEnabled: false,
                    callbackReceivers: [{type: 1,service: '',path: ''}],
                    callbackRespHeaders: [{key: '',value: ''}],
                    apps: [],
                    apiPlugins: []
                },
                groupList: [],
                appData: [],
                drawer: false,
                pluginList: [],
                addTempPlugin: [],
                // 后端订阅集合
                appDrawer: false,
                serviceList: [],
                checkedList: [],
                 mode: 'add',
                 methods: ['GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS','TRACE'],
                 addForm: {},
                 rules: {
                     gatewayGroup: [{required: true, message: '必填', trigger: 'blur'}],
                     service: [{required: true, message: '必填', trigger: 'blur'}],
                     path: [{required: true, message: '必填', trigger: 'blur'}],

                 },
                serviceForm: {
                    type: 1,
                    service: '',
                    path: ''
                },
                formTitle: '新增回调配置',
                appTotal: 0,
                queryParams: {}
            }
        },
        mounted() {
            this.getGroupData();
            this.getDictList();
            this.mode = this.$route.params.detail;
            if(this.mode === 'edit' || this.mode === 'view') {
                const id = this.$route.query.originId
                this.getConfigDetail(id);
            }
            if(this.mode === 'view') {
                this.formTitle = '查看回调配置';
                
            }
        },
        methods: {
            async getConfigDetail(id) {
                const result = await getDetail(id);
                 if(result.code === 200) {
                    this.form = result.data;
                }
            },
            addAppClick() {
                const data = this.$refs.appRef.selection.map(item => {
                    return {
                        enabled: true,
                        app: item.app,
                        appName: item.appName
                    }
                })
                this.form.apps.push(...data);
                this.appDrawer = false;
            },
            handleDelete(index) {
                this.form.apps.splice(index,1);
            },
            // 搜索
            handleQuery() {
                this.queryParams.current = 1;
                this.getList();
            },
            // 清空
            resetQuery(formName) {
                this.$refs[formName].resetFields();
                this.getList();
            },
            handleSizeChange(val) {
                this.queryParams.size = val;
                this.getList();
           },
            handleCurrentChange(val) {
                this.queryParams.current = val;
                this.getList();
            },
            async getList() {
                const result = await getAppIdList(this.queryParams);
                if(result.code === 200) {
                    this.appData = result.data.records;
                    this.appTotal = result.total;
                }
            },
            handleCheckAllChange(val) {
                if(val) {
                    this.pluginList.forEach(item=>item.check=true)
                }else {
                    this.pluginList.forEach(item=>item.check=false)
                }
             },
            async addPlugin() {
                this.drawer = true;
                const result = await getPluginListAll();
                if(result.code === 200) {
                    this.pluginList = result.data;
                }
            },
            handleCancel() {
                this.$router.push('/gateway/group');
            },
            handleAddPlugin() {
                  this.form.apiPlugins.push(...this.pluginList.filter(item=>item.check));
                  this.drawer = false;
            },
            addSubscribe() {
                this.form.callbackReceivers.push({type: 1,service: '',path: ''});
            },
            handleDetele(item) {
                 const index = this.form.callbackReceivers.indexOf(item)
                 if (index !== -1) {
                    this.form.callbackReceivers.splice(index, 1)
                 }
            },
            async getGroupData() {
                const result = await getGroupList();
                if(result.code === 200) {
                    this.groupList = result.data;
                }
            },
            async getDictList() {
                const result = await getServiceList();
                if(result.code === 200) {
                    this.serviceList = result.data;
                }
            },
            handleAddRes() {
                this.form.callbackRespHeaders.push({key:'',value: ''});
            },
            removeRes(item) {
                 const index = this.form.callbackRespHeaders.indexOf(item)
                 if (index !== -1) {
                    this.form.callbackRespHeaders.splice(index, 1)
                 }
            },
            handleClose() {},
            handleChange(item) {
                if(item.checked) {
                    this.addTempPlugin.push(item);
                }else {
                    this.addTempPlugin.remove(item);
                }
            },
            async handleAddApp() {
                this.appDrawer = true;
                this.getList();
            },
            savePlugin() {
                this.form.apiPlugins = this.addTempPlugin;
                this.drawer = false;
            },
             handleSubmit(formName) {
                 this.$refs[formName].validate(async(valid) => {
                 if (valid) {
                     this.form.proxyMode = 4;
                     if(this.form.callbackType === 's') {
                         delete this.form.callbackRespHeaders;
                     }
                    this.form.apiPlugins.forEach(item=>{
                        item.plugin = item.id;
                        item.id = null;
                    })
                     const result = await save(this.form);
                     if(result.code === 200) {
                        this.$message.success('保存成功');
                        this.$router.push('/gateway/group');
                     }
                  } else {
                    return false;
                }
              });
            }
        }
    }
</script>

<style lang="scss" scoped>
.detele-wrap {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: #e94444;
    color: #fff;
    font-size: 15px;
    text-align: center;
    line-height: 30px;
    margin-left: 10px;
    margin-top: 6px;
}
.title {
    margin-left: 10px;
    font-weight: 600;
    font-size: 16px;
}
</style>